<template>
  <a-card :bordered='false'>
    <!-- 操作按钮区域 -->
    <div class='table-operator'>
      <a-button @click='handleAdd' type='primary' icon='plus'>新增</a-button>
    </div>
    <div>
      <div class='ant-alert ant-alert-info' style='margin-bottom: 16px'>
        <i class='anticon anticon-info-circle ant-alert-icon'></i> 已选择
        <a style='font-weight: 600'>{{ selectedRowKeys.length }}</a
        >项
      </div>
      <a-table
        ref='table'
        size='middle'
        rowKey='id'
        :columns='columns'
        :dataSource='dataSource'
        :pagination='ipagination'
        childrenColumnName='childrenList'
        :loading='loading'
        @change='handleTableChange'
        v-bind='tableProps'
      >
        <span slot='action' slot-scope='text, record'>
          <a @click='handleEdit(record)'>编辑</a>
          <a-divider type='vertical' />
          <a-popconfirm title='确定删除吗?' @confirm='() => handleDelete(record)'>
            <a>删除</a>
          </a-popconfirm>
          <a-divider type='vertical' />
          <!-- <a @click="handleAddSub(record)">添加下级</a> -->
        </span>
      </a-table>
    </div>
    <a-modal v-model='serviceAdd' :title='title' @ok='handleOk' @cancel='onColse'>
      <a-form :form='modelAdd' :label-col='{ span: 5 }' :wrapper-col='{ span: 12 }'>
        <a-form-item label='父级节点'>
          <a-select
            v-model='modelAdd.pid'
            placeholder='请选择父级节点'
            @change='handleSelectChange'
          >
            <a-select-option
              v-for='item in ParentNodeOptions'
              :key='item.value'
              :value='item.value'
              :label='item.label'
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label='分类名称'>
          <a-input v-model='modelAdd.name' placeholder='分类名称不能为空' />
        </a-form-item>
        <a-form-item label='所属部门'>
          <a-select
            v-model='modelAdd.deptId'
            placeholder='请选择部门'
            @change='deptChange'
          >
            <a-select-option
              v-for='item in deptOptions'
              :key='item.value'
              :value='item.value'
              :label='item.label'
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label='服务节点'>
          <a-input v-model='modelAdd.serviceNode' placeholder='服务节点不能为空' />
        </a-form-item>
        
        <a-form-item
        label="服务icon">
        <a-upload
          :headers="headers"
          :action="uploadAction"
          list-type="picture-card"
          :file-list="fileIconList"
          @preview="handlePreview"
          @change="handleChange"
          :class="[fileIconList.length > 1 ? 'image-upload-single-over' : '']"
        >
          <div v-if="fileIconList.length < 1">
            <a-icon type="plus" />
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
        
        <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
  import Vue from 'vue'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
import {
  queryAll,
  JbdServiceAdd,
  JbdServiceEdit,
  JbdServiceDelete,
  JbdServiceQueryList,
  DepartQueryTreeList
} from '@/api/service.js'

export default {
  name: 'SysCategoryList',
  data() {
    return {
      description: '分类字典管理页面',
      // 表头
      columns: [
        {
          title: '分类名称',
          align: 'left',
          dataIndex: 'name'
        },
        {
          title: '所属部门',
          align: 'left',
          dataIndex: 'departName'
        },
        {
          title: '服务节点',
          align: 'left',
          dataIndex: 'serviceNode',
          customRender: function(text) {
            if (text !== null) {
              return text.toString()
            } else {
              return ''
            }
          }
        },
        {
          title: '创建人',
          align: 'left',
          dataIndex: 'createBy'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      serviceAdd: false, // 服务新增弹框
      modelAdd: {
        pid: '一级类目',
        name: '',
        isLevel1: '',
        deptId:'',
        serviceNode: ''
      }, // 新增数据,
      dataSource: [], // 列表数据
      ParentNodeOptions: [], // 父级节点
      deptOptions: [],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      loading: false,
      expandedRowKeys: [],
      hasChildrenField: 'hasChild',
      pidField: 'pid',
      dictOptions: {},
      subExpandedKeys: [],
      selectedRowKeys: [],
      title: '',
      fileIconList:[],
      previewVisible: false,
      previewImage: '',
      headers: {},
      uploadAction: window._CONFIG['domianURL'] + '/sys/common/upload'
    }
  },
  mounted() {
    const token = Vue.ls.get(ACCESS_TOKEN)
    this.headers = { 'X-Access-Token': token }
    this.getList()
  },
  methods: {
    //  获取列表
    async getList() {
      this.loading = true
      const res = await queryAll()
      if (res.success) {
        this.dataSource = res.result
        this.loading = false
      }
    },
    // 新增类别
    handleAdd() {
      this.getOptions()
      this.getDepart()
      this.title = '新增'
      this.serviceAdd = true
    },
    async getOptions() {
      const res = await JbdServiceQueryList()
      this.ParentNodeOptions = res.result.map((item) => {
        return {
          label: item.name,
          value: item.id
        }
      })
    },
    async getDepart() {
      const res = await DepartQueryTreeList()
      this.deptOptions = res.result.map((item) => {
        return {
          label: item.departName,
          value: item.id
        }
      })
    },
    async handleOk() {
      if (this.modelAdd.name == '') {
        this.$message.error('分类名称不能为空')
      } else if (this.modelAdd.deptId == '') {
        this.$message.error('所选部门不能为空')
      }else if (this.modelAdd.serviceNode == '') {
        this.$message.error('服务节点不能为空')
      } 
      else if (!this.fileIconList.length) {
        this.$message.error('服务icon不能为空')
      } 
      else {
        const createBy = JSON.parse(window.localStorage.getItem('pro__Login_Userinfo'))
          .value.username
        if (this.modelAdd.pid == '一级类目' || this.modelAdd.pid == '一级类目') {
          this.modelAdd.isLevel1 = 1
        } else {
          this.modelAdd.isLevel1 = 0
        }
        if (this.title == '新增') {
          if (this.modelAdd.serviceNode !== '' && this.modelAdd.serviceNode !== null) {
            this.modelAdd.serviceNode = this.modelAdd.serviceNode.split(',')
          }
          let icon = this.fileIconList[0].response.message;
          if(this.modelAdd.pid == '一级类目'){
            const pid = '0';
            const params = {
              icon:icon,
              createBy,
              pid: pid,
              name: this.modelAdd.name,
              isLevel1: this.modelAdd.isLevel1,
              deptId: this.modelAdd.deptId,
              serviceNode: this.modelAdd.serviceNode
            }
            const res = await JbdServiceAdd(params)
            if (res.code == 200) {
              this.$message.success('添加成功')
              this.serviceAdd = false
              this.getList()
            }
          }else{
            const params = {
              icon:icon,
              createBy,
              pid: this.modelAdd.pid,
              name: this.modelAdd.name,
              isLevel1: this.modelAdd.isLevel1,
              deptId: this.modelAdd.deptId,
              serviceNode: this.modelAdd.serviceNode
            }
            const res = await JbdServiceAdd(params)
            if (res.code == 200) {
              this.$message.success('添加成功')
              this.serviceAdd = false
              this.getList()
            }
          }

        } else {
          let icon = this.fileIconList[0].response.message;
          const updateBy = JSON.parse(window.localStorage.getItem('pro__Login_Userinfo')) .value.username
          if (Array.isArray(this.modelAdd.serviceNode) == false) {
            if (this.modelAdd.serviceNode !== '' && this.modelAdd.serviceNode !== null) {
              this.modelAdd.serviceNode = this.modelAdd.serviceNode.split(',')
            }
          }
          if(this.modelAdd.pid == '一级类目'){
            const pid = '0';
            const params = {
              icon:icon,
              id: this.modelAdd.id,
              pid: pid,
              name: this.modelAdd.name,
              isLevel1: this.modelAdd.isLevel1,
              deptId: this.modelAdd.deptId,
              serviceNode: this.modelAdd.serviceNode,
              updateBy
            }
            const result = await JbdServiceEdit(params)
            if (result.code == 200) {
              this.$message.success('编辑成功')
              this.serviceAdd = false
              this.getList()
            }
          }else{
            const params = {
              icon:icon,
              id: this.modelAdd.id,
              pid: this.modelAdd.pid,
              name: this.modelAdd.name,
              isLevel1: this.modelAdd.isLevel1,
              deptId: this.modelAdd.deptId,
              serviceNode: this.modelAdd.serviceNode,
              updateBy
            }
            const result = await JbdServiceEdit(params)
            if (result.code == 200) {
              this.$message.success('编辑成功')
              this.serviceAdd = false
              this.getList()
            }
          }

        }
      }
    },
    handleTableChange() {
    },
    handleEdit(record) {
      this.$set(this.modelAdd, 'id', record.id)
      if(record.pid == '0' ||record.pid=='1'){
        this.$set(this.modelAdd, 'pid', '一级类目')
      }else{
        this.$set(this.modelAdd, 'pid', record.pid)
      }
      this.$set(this.modelAdd, 'name', record.name)
      this.$set(this.modelAdd, 'deptId', record.deptId)
      this.$set(this.modelAdd, 'serviceNode', record.serviceNode)
      this.$set(this.modelAdd, 'isLevel1', record.isLevel1)
      console.log(record.icon,"588585")
      this.fileIconList = [];
      let obj = {
        response: record.icon,
        uid: record.icon,
        status: 'done',
        name: record.icon,
        url: 'https://jbd.iminggu.com/jeecg-boot/sys/common/static/'+record.icon
      }
      this.fileIconList.push(obj)
      this.getOptions()
      this.getDepart()
      this.title = '编辑'
      this.serviceAdd = true
    },
    onColse() {
      this.title = ''
      this.$set(this.modelAdd, 'id', '')
      this.$set(this.modelAdd, 'pid', '一级类目')
      this.$set(this.modelAdd, 'name', '')
      this.$set(this.modelAdd, 'deptId', '')
      this.$set(this.modelAdd, 'serviceNode', '')
      this.$set(this.modelAdd, 'isLevel1', '')
    },
    async handleDelete(record) {
      const params = {
        id: record.id
      }
      const res = await JbdServiceDelete(params)
      if (res.code == 200) {
        this.$message.success('删除成功')
        this.getList()
      }
      console.log(res)
    },
    handleAddSub() {
    },
    deptChange(val) {
      this.$set(this.modelAdd, 'deptId', val)
    },
    handleSelectChange(val) {
      this.$set(this.modelAdd, 'pid', val)
    },
    
    // 预览
    handlePreview(file) {
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    handleChange({fileList}) {
      this.fileIconList = fileList;
    },
    handleCancel() {
      this.previewVisible = false
    },
  }
  ,
  computed: {
    tableProps() {
      let _this = this
      return {
        // 列表项是否可选择
        rowSelection: {
          selectedRowKeys: _this.selectedRowKeys,
          onChange: (selectedRowKeys) => (_this.selectedRowKeys = selectedRowKeys)
        }
      }
    }
  }
}
</script>
<style scoped>
@import "~@assets/less/common.less";
</style>
